package com.qike.duola.service.impl;

import com.alibaba.fastjson.JSON;
import com.qike.duola.domain.SysResource;
import com.qike.duola.domain.SysResourceExample;
import com.qike.duola.domain.SysUser;
import com.qike.duola.domain.SysUserWithBLOBs;
import com.qike.duola.dto.*;
import com.qike.duola.enums.StatusEnums;
import com.qike.duola.mapper.SysResourceMapper;
import com.qike.duola.service.DuolaTransOrderService;
import com.qike.duola.service.IsysResourceService;
import com.qike.duola.utils.SubjectUtil;
import com.qike.duola.vo.MenuListVo;
import com.qike.duola.vo.ResourceListByParentIdVo;
import com.qike.duola.vo.ResourceListVo;
import com.qike.duola.vo.ResourceVo;
import io.swagger.annotations.ApiModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: Eric.zhou
 * @Date: 2020/7/31 12:23
 */
@Service
public class SysResourceServiceImpl implements IsysResourceService {

    private static final Logger logger= LoggerFactory.getLogger(SysResourceServiceImpl.class);

    @Resource
    private SysResourceMapper sysMenuMapper ;



    @Override
    public ResourceListVo getMenuList(Long uid) {
        ResourceListVo vo = new ResourceListVo();
        List<Long> listVos = new ArrayList<>();
        if (uid==null){
            uid = (Long) SecurityUtils.getSubject().getPrincipal();
        }
//        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
        //根据用户id查询用户角色
        List<SysResource> menuList = sysMenuMapper.selectList(uid);
        if (menuList.size()>0){
            for (SysResource sysResource : menuList) {
                listVos.add(sysResource.getId());
            }
        }
        //todo 获取所有菜单
        ResourceListVo listVo = this.resourceList(new ResourceListDto());

        List<ResourceVo> list1 = listVo.getList();
        //todo 比对两个菜单
        this.checkMenu(listVo.getList(), listVos);
        vo.setList(list1);
        return vo;
    }

    /**
     * 在已有的权限上选中
     */
    private void checkMenu(List<ResourceVo> list, List<Long> haveIds) {
        for (ResourceVo resourceRoleInfoVo : list) {
            if (haveIds.contains(resourceRoleInfoVo.getId())){
                resourceRoleInfoVo.setCheck(true);
            }else {
                resourceRoleInfoVo.setCheck(false);
            }
            if (resourceRoleInfoVo.getChild().size() > 0) {
                this.checkMenu(resourceRoleInfoVo.getChild(), haveIds);
            }

        }

    }

    public List<MenuListVo> getMenuListByRoleId(Long roleId) {

        List<MenuListVo> listVos = new ArrayList<>();

//        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
        //根据用户id查询用户角色
        List<SysResource> menuList = sysMenuMapper.selectListByRoleId(roleId);
        if (menuList.size()>0){
            for (SysResource sysResource : menuList) {
                MenuListVo vo = new MenuListVo();
                vo.setId(sysResource.getId());
                vo.setName(sysResource.getName());
                vo.setPath(sysResource.getUrl());
                vo.setSort(sysResource.getSort());
                listVos.add(vo);
            }
        }
        return listVos;
    }

    /**
     * 权限列表
     *
     * @param resourceListDto
     * @return
     */
    @Override
    public ResourceListVo resourceList(ResourceListDto resourceListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"权限列表"+ JSON.toJSON(resourceListDto));
        ResourceListVo listVo = new ResourceListVo();
        List<ResourceVo> list = new ArrayList<>();
        SysResourceExample example = new SysResourceExample();
        example.createCriteria().andParentIdEqualTo(0L).andStatusEqualTo(Boolean.TRUE);
        example.setOrderByClause("sort asc");
        List<SysResource> parentList = sysMenuMapper.selectByExample(example);
        for (SysResource sysResource : parentList) {
            ResourceVo vo = new ResourceVo();
            vo.setId(sysResource.getId());
            vo.setName(sysResource.getName());
            vo.setIcon(sysResource.getIcon());
            vo.setSort(sysResource.getSort());
            vo.setUrl(sysResource.getUrl());
            vo.setParentId(sysResource.getParentId());
            vo.setChild(getChildren(sysResource.getId()));
            list.add(vo);
        }
        listVo.setList(list);
        return listVo;
    }

    /**
     * 添加权限
     *
     * @param resourceListDto
     */
    @Override
    public void resourceAdd(ResourceAddDto resourceListDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"添加权限"+ JSON.toJSON(resourceListDto));
        SysResource sysResource = new SysResource();
        sysResource.setCreateAt(new Date());
        sysResource.setPermission(resourceListDto.getPermission());
        sysResource.setCreateBy(userId);
        sysResource.setStatus(Boolean.TRUE);
        sysResource.setUrl(resourceListDto.getUrl());
        sysResource.setName(resourceListDto.getName());
        sysResource.setParentId(resourceListDto.getParentId());
        sysResource.setType(resourceListDto.getType());
        sysMenuMapper.insertSelective(sysResource);

    }

    /**
     * 删除权限
     *
     * @param resourceDelDto
     */
    @Override
    public void resourceDel(ResourceDelDto resourceDelDto) throws Exception {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"删除权限"+ JSON.toJSON(resourceDelDto));
        SysResource sysResource = sysMenuMapper.selectByPrimaryKey(resourceDelDto.getId());
        if (sysResource==null){
            throw new Exception("数据异常");
        }
        sysResource.setStatus(Boolean.FALSE);
        sysResource.setUpdateBy(userId);
        sysResource.setUpdateAt(new Date());
        sysMenuMapper.updateByPrimaryKeySelective(sysResource);
    }

    /**
     * 编辑权限
     *
     * @param resourceEditDto
     */
    @Override
    public void resourceEdit(ResourceEditDto resourceEditDto) {
        Long userId = (Long) SecurityUtils.getSubject().getPrincipal();
        logger.info(userId+"编辑权限"+ JSON.toJSON(resourceEditDto));
        SysResource sysResource = sysMenuMapper.selectByPrimaryKey(resourceEditDto.getId());
        sysResource.setParentId(resourceEditDto.getParentId());
        sysResource.setName(resourceEditDto.getName());
        sysResource.setUrl(resourceEditDto.getUrl());
        sysResource.setUpdateBy(userId);
        sysResource.setUpdateAt(new Date());
        sysMenuMapper.updateByPrimaryKeySelective(sysResource);
    }

    /**
     * 资源管理列表 parentID不传获取所有父级资源 id获取某一条数据
     *
     * @param parentId
     * @param id
     * @return
     */
    @Override
    public List<ResourceListByParentIdVo> resourceListByParentId(Long parentId, Long id) {
        List<ResourceListByParentIdVo> list = new ArrayList<>();
        SysResourceExample example = new SysResourceExample();
        SysResourceExample.Criteria criteria = example.createCriteria();
        if (parentId!=null){
            criteria.andParentIdEqualTo(parentId);
        }else {
            criteria.andParentIdEqualTo(0L);
        }
        if (id!=null){
            example.clear();
            example.createCriteria().andIdEqualTo(id);
//            criteria.andIdEqualTo(id);
        }
        List<SysResource> sysResources = sysMenuMapper.selectByExample(example);
        for (SysResource sysResource : sysResources) {
            ResourceListByParentIdVo vo = new ResourceListByParentIdVo();
            vo.setId(sysResource.getId());
            vo.setName(sysResource.getName());
            list.add(vo);
        }
        return list;
    }

    /**
     * 资源管理列表 parentID不传获取所有父级资源 id获取某一条数据
     *
     * @param parentId
     * @param name
     * @return
     */
    @Override
    public List<ResourceListByParentIdVo> resourceListByParentIdAndName(Long parentId, String name) {
        List<ResourceListByParentIdVo> list = new ArrayList<>();
        SysResourceExample example = new SysResourceExample();
        SysResourceExample.Criteria criteria = example.createCriteria();
        if (parentId!=null) {
            criteria.andParentIdEqualTo(parentId);
        }
        if (!StringUtils.isEmpty(name)){
            criteria.andNameLike(name);
//            criteria.andIdEqualTo(id);
        }
        List<SysResource> sysResources = sysMenuMapper.selectByExample(example);
        for (SysResource sysResource : sysResources) {
            ResourceListByParentIdVo vo = new ResourceListByParentIdVo();
            vo.setId(sysResource.getId());
            vo.setName(sysResource.getName());
            list.add(vo);
        }
        return list;
    }


    private  List<ResourceVo> getChildren(Long id){
        List<ResourceVo> voList = new ArrayList<>();
        SysResourceExample example = new SysResourceExample();
        example.createCriteria().andParentIdEqualTo(id).andStatusEqualTo(Boolean.TRUE);
        example.setOrderByClause("sort asc");
        List<SysResource> treeList = sysMenuMapper.selectByExample(example);
        for (SysResource sysResource : treeList) {
            ResourceVo vo = new ResourceVo();
            vo.setId(sysResource.getId());
            vo.setName(sysResource.getName());
            vo.setIcon(sysResource.getIcon());
            vo.setUrl(sysResource.getUrl());
            vo.setParentId(sysResource.getParentId());
            vo.setSort(sysResource.getSort());
            vo.setChild(getChildren(sysResource.getId()));
            voList.add(vo);
        }

        return voList;
    }

}
